package com.deep.deepenterpise.common.util;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author xyz
 * @version 1.0
 * @title MD5Util
 * @description
 * @create 2024/5/7 11:00
 */
@Slf4j
public class DrMD5Util {
    private DrMD5Util() {
    }

    /**
     * @return java.lang.String
     * @Auth xyz
     * @Desc //TODO 将字节数组转换为十六进制字符串
     * @Time 11:01 2024/5/7
     * @Param [bytes]
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte aByte : bytes) {
            result.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
        }
        return result.toString();
    }

    /**
     * @return java.lang.String
     * @Auth xyz
     * @Desc //TODO 计算字符串的MD5哈希值
     * @Time 11:01 2024/5/7
     * @Param [input]
     */
    public static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            return bytesToHex(messageDigest);
        } catch (NoSuchAlgorithmException e) {
            log.error("[MD5加密失败]-------{}", DrCommonUtil.drGetStackTraceInfo(e));
            return null;
        }
    }
}
